package com.prs.crm.action.cqunicom;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.UserLoginStore;
import com.prs.crm.domain.cqunicom.Company;
import com.prs.crm.domain.cqunicom.LogSerch;
import com.prs.crm.domain.cqunicom.MidBusinessOrder;
import com.prs.crm.domain.cqunicom.MonitorOrder;
import com.prs.crm.domain.cqunicom.Services;
import com.prs.crm.domain.cqunicom.ServicesType;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.service.cqunicom.CompanyService;
import com.prs.crm.service.cqunicom.LogSerchService;
import com.prs.crm.service.cqunicom.MidBusinessOrderService;
import com.prs.crm.service.cqunicom.MonitorOrderService;
import com.prs.crm.service.cqunicom.NoteInformationService;
import com.prs.crm.service.cqunicom.ServicesService;
import com.prs.crm.service.cqunicom.ServicesTypeService;
import com.prs.crm.service.hr.PersonService;
import com.prs.crm.service.sys.LogService;
/**
 * @author  WangTing
 *
 * 创建时间：2011-3-4 
 * 
 */

public class CompanyAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private LogSerch logSerch;	
	private LogSerchService logSerchService;
	private Company company;
	private CompanyService companyService;
	private MidBusinessOrder midBusinessOrder;
	private Person person;
	private PersonService personService;
	private MidBusinessOrderService midBusinessOrderService;
	private Services services;
	private ServicesService servicesService;
	private ServicesType servicesType;
	private ServicesTypeService servicesTypeService;
	private List<ServicesType> types;
	private NoteInformationService noteInformationService;
	private List<Services> servicesList=new ArrayList<Services>();
	private List<MidBusinessOrder> midList;
	private MonitorOrderService monitorOrderService;
	private MonitorOrder monitorOrder;
	private Integer companyIds=0;
	private String pass;
	private String serverNames="";
	private Date currentDate;
	private String comName;
	private  Integer design;
	private Company companyss;
	private boolean flag;
	private PaginationSupport pagination;
	private LogService logService;
	private  String serial_number;
	Collection<Company>   companys;
	private String serverids;
	@Action("editCompany")
	public String edit() {
		currentDate = new Date();
		
		serial_number=create();
		
		this.types = this.getServicesTypeService().getAllServicesType();
		if(company!=null){
		Company com=this.getCompanyService().get(company.getId());
		midList=this.getMidBusinessOrderService().getMidBusinessOrderBycomp(com);
		for(MidBusinessOrder mid:midList){
			servicesList.add(mid.getServicesm());
			if("".equals(serverNames)){
			serverNames=mid.getServicesm().getId()+"";
			}else{
				serverNames=serverNames+","+mid.getServicesm().getId();
			}
		}
		}
		return SUCCESS;
	}
	
	@Action("selectServices")
	public String selectServices() {

		
		ServicesType  kk=this.getServicesTypeService().get(design);
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Services.class);
		criteria.add(Restrictions.eq("servicesType",kk));	
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getServicesService().listByPage(criteria,
				pagination));
		

		return SUCCESS;
	}
	
	@Action("selectServicesType")
	public String selectServicesType() {

		
		
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				ServicesType.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getServicesTypeService().listByPage(criteria,
				pagination));
		

		return SUCCESS;
	}
	
	@Action("viewCompany")
	public String view() {
		Company com=this.getCompanyService().get(company.getId());
		midList=this.getMidBusinessOrderService().getMidBusinessOrderBycomp(com);
		for(MidBusinessOrder ss:midList){
			if("".equals(serverNames)){
				serverNames=ss.getServicesm().getName();	
			}else{
				serverNames=serverNames+","+ss.getServicesm().getName();
			}
				
		}
		
		
		
		return SUCCESS;
	}
	/**
	 * 商家查看
	 * @return
	 */
	@Action("listCompany")
	public String listCompany() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Company.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.addOrder(Order.asc("sortNums"));
		
		this.setPagination(this.getCompanyService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	/**
	 * 商家查看
	 * @return
	 */
	@Action("selectCompanyOrder")
	public String selectCompanyOrder() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Company.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.addOrder(Order.asc("sortNums"));
		this.setPagination(this.getCompanyService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	/**
	 * 商家变更
	 * @return
	 */
	@Action("listupCompany")
	public String listupCompany() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Company.class);
		pagination = this.getPaginationHelper().prepare(pagination);
//		criteria.addOrder(Order.asc("sortNums"));
		criteria.addOrder(Order.asc("sortNums"));
		this.setPagination(this.getCompanyService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	
	@Clew(results = { "success", "none" })
	@Action(value = "saveCompany", results = {
			@Result(name = "success", type = "redirect", location = "editCompany"),
			@Result(name = "none", type = "redirect", location = "listCompany"),
			@Result(name = "error", type = "chain", location = "editCompany") })
	public String save() {
	int k=0; 
	if(company.getId()==null){
		//日志
		LogSerch  log=new LogSerch();
		log.setCandlePeron(AppContext.getAccountContext().currentUser().getUserName());
		log.setCandleContents("注册了新商家:"+company.getComName());
		this.getLogSerchService().save(log);
		k++;
	}else{
		//日志
		LogSerch  log=new LogSerch();
		log.setCandlePeron(AppContext.getAccountContext().currentUser().getUserName());
		log.setCandleContents("修改了商家:"+company.getComName()+"信息");
		this.getLogSerchService().save(log);
		
	}
		
		
		   int leves=1;
		   int levesNums=0;
		   if("一级".equals(company.getLevel())){
			   leves=1; 
			   levesNums=5;
		   }
		   else if("二级".equals(company.getLevel())){
			   leves=1; 
			   levesNums=4;
		   }
		   else if("三级".equals(company.getLevel())){
			   leves=1; 
			   levesNums=3;
		   }
		   else if("四级".equals(company.getLevel())){
			   leves=1; 
			   levesNums=2;
		   }
		   else if("五级".equals(company.getLevel())){
			   leves=1; 
			   levesNums=1;
		   }
		   company.setLevels(leves);
		   company.setClickTimes(levesNums);
		   company.setSortNums(leves*levesNums);
		   this.getCompanyService().save(company);
		   
		   String servers[]=serverids.split(",");
		  
		   if(k>0){
			   for(String ser:servers){
				   Services  svice=this.getServicesService().get(Integer.parseInt(ser));
				
				   MidBusinessOrder  mid=new MidBusinessOrder();   
				   mid.setCompanym(company);
			
				   mid.setServicesm(svice);
				   this.getMidBusinessOrderService().save(mid);
			
			   } 
		   }else{
			   List<MidBusinessOrder> dd=this.getMidBusinessOrderService().getMidBusinessOrderBycomp(company);
			   
			   for(MidBusinessOrder sers:dd){
				   int kk=0;
				   for(String ser:servers){
					   Services  svice=this.getServicesService().get(Integer.parseInt(ser));
				   if(sers.getServicesm()==svice){
					   kk++;
				   }
				   
				   }
				   if(kk==0){
					   this.getMidBusinessOrderService().remove(sers);
				   }
			   }
			 
		   }
		   
		   this.setPrompt("操作成功") ;
		   return SUCCESS;
	}

	@Action("editComRegister1")
	public String editComRegister1()
	{
		return SUCCESS;
		
	}
	
	@Action(value = "SubmitComRegister1", results = {
			@Result(name = "success", type = "redirect", location = "editComRegister2?design=${companyss.getId()}"),
			@Result(name = "error", type = "chain", location = "editComRegister1") })
	public String SubmitComRegister1()
	{
   
	   companyss=this.getCompanyService().getCompanyBySerialNum(company.getSerial_number());
	 
	   if(companyss==null ){
		  
		   this.addActionError("序列号不存在");
		   return ERROR;
	   }
	   else{
		   flag=this.getCompanyService().existSameNum(company.getSerial_number());
		   if(flag=false){
				
				this.addActionError("序列号错误");
				return ERROR;
				
			}else{
				
				 return SUCCESS;
			}
		   
	   }

		
	}
	
	@Action("editComRegister2")
	public String editComRegister2()
	{
		
		Company company2=this.getCompanyService().get(design);
	
		comName=company2.getComName();
	
		return SUCCESS;
		
	}
	
	@Action(value = "saveComRegister2", results = {
			@Result(name = "success", type = "redirect", location ="../index"),
			@Result(name = "error", type = "chain", location = "editComRegister2") })
	public String saveComRegister2()
	{
		Person account = AppContext.getAccountContext().getUser();
		UserLoginStore.removeUser(account);
		  List<Person> per=this.getPersonService().getAllPersons();
	        int diacInit=0;
	        for(Person p:per){
	        	if(p.getLoginCode().equals(person.getLoginCode())){
	        		diacInit++;
	        	}
	        }
	        if (isnull(person.getUserEmail())) {
				if (emailFormat(person.getUserEmail())) {
					this.addActionError("邮箱格式不对");
					return ERROR;
				}
			}    
	        
	    if(diacInit>0){
	    	this.setPrompt("登录用户名重复");
	    	return "error";
	    }else{
	    	this.setPrompt("商家注册成功");
	    	this.getPersonService().save(person);
	    	return SUCCESS;
	    }  
	    
		
			
	}
	
	

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Services getServices() {
		return services;
	}

	public String getServerNames() {
		return serverNames;
	}

	public void setServerNames(String serverNames) {
		this.serverNames = serverNames;
	}

	public void setServices(Services services) {
		this.services = services;
	}

	public ServicesService getServicesService() {
		return servicesService;
	}

	public void setServicesService(ServicesService servicesService) {
		this.servicesService = servicesService;
	}

	
	public PaginationSupport getPagination() {
		return pagination;
	}
	public LogService getLogService() {
		return logService;
	}
	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public Company getCompany() {
		return company;
	}



	public Integer getDesign() {
		return design;
	}

	public void setDesign(Integer design) {
		this.design = design;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	

	public Integer getCompanyIds() {
		return companyIds;
	}

	public void setCompanyIds(Integer companyIds) {
		this.companyIds = companyIds;
	}

	public ServicesType getServicesType() {
		return servicesType;
	}

	public void setServicesType(ServicesType servicesType) {
		this.servicesType = servicesType;
	}

	public ServicesTypeService getServicesTypeService() {
		return servicesTypeService;
	}

	public void setServicesTypeService(ServicesTypeService servicesTypeService) {
		this.servicesTypeService = servicesTypeService;
	}

	
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public List<ServicesType> getTypes() {
		return types;
	}

	public void setTypes(List<ServicesType> types) {
		this.types = types;
	}

	public List<Services> getServicesList() {
		return servicesList;
	}

	public void setServicesList(List<Services> servicesList) {
		this.servicesList = servicesList;
	}

	

	public Date getCurrentDate() {
		return currentDate;
	}

	public void setCurrentDate(Date currentDate) {
		this.currentDate = currentDate;
	}

	public String  create(){
		UUID uuid= UUID.randomUUID();   
		String sn=uuid.toString();
		return sn;
	
	}

	public String getSerial_number() {
		return serial_number;
	}

	public void setSerial_number(String serial_number) {
		this.serial_number = serial_number;
	}
	public boolean istel(String str) {
		boolean tag = false;  
		final String pattern1 = "^(([0-9]{3,4})|[0-9]{3,4}-)?[0-9]{7,8}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(str);
		if (!mat.find()) {
			tag = true;
		}
		return tag;
	}

	public boolean isnull(String str) {
		boolean s=true;
		if (str.trim().equals("") || str == null) {
			s= false;
		}
		return s;
	}

	public Collection<Company> getCompanys() {
		return companys;
	}

	public String getServerids() {
		return serverids;
	}

	public void setServerids(String serverids) {
		this.serverids = serverids;
	}

	public void setCompanys(Collection<Company> companys) {
		this.companys = companys;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public NoteInformationService getNoteInformationService() {
		return noteInformationService;
	}

	public void setNoteInformationService(
			NoteInformationService noteInformationService) {
		this.noteInformationService = noteInformationService;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public Company getCompanyss() {
		return companyss;
	}

	public void setCompanyss(Company companyss) {
		this.companyss = companyss;
	}

	public String getComName() {
		return comName;
	}

	public void setComName(String comName) {
		this.comName = comName;
	}
	public boolean emailFormat(String email) {
		boolean tag = false;
		final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(email);
		if (!mat.find()) {
			tag = true;
		}
		return tag;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public PersonService getPersonService() {
		return personService;
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}



	public MidBusinessOrder getMidBusinessOrder() {
		return midBusinessOrder;
	}

	public void setMidBusinessOrder(MidBusinessOrder midBusinessOrder) {
		this.midBusinessOrder = midBusinessOrder;
	}

	public MidBusinessOrderService getMidBusinessOrderService() {
		return midBusinessOrderService;
	}

	public void setMidBusinessOrderService(
			MidBusinessOrderService midBusinessOrderService) {
		this.midBusinessOrderService = midBusinessOrderService;
	}

	

	public List<MidBusinessOrder> getMidList() {
		return midList;
	}

	public void setMidList(List<MidBusinessOrder> midList) {
		this.midList = midList;
	}

	public MonitorOrderService getMonitorOrderService() {
		return monitorOrderService;
	}

	public void setMonitorOrderService(MonitorOrderService monitorOrderService) {
		this.monitorOrderService = monitorOrderService;
	}

	public MonitorOrder getMonitorOrder() {
		return monitorOrder;
	}

	public void setMonitorOrder(MonitorOrder monitorOrder) {
		this.monitorOrder = monitorOrder;
	}

	public LogSerch getLogSerch() {
		return logSerch;
	}

	public void setLogSerch(LogSerch logSerch) {
		this.logSerch = logSerch;
	}

	public LogSerchService getLogSerchService() {
		return logSerchService;
	}

	public void setLogSerchService(LogSerchService logSerchService) {
		this.logSerchService = logSerchService;
	}
	
}
